package cn.Mmovie.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "AdminAuthenticationFilter",urlPatterns = "/admin/*")
public class AdminAuthenticationFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("AdminAuthenticationFilter doFilter...");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        if(!request.getServletPath().equals("/login")
                && !request.getServletPath().equals("/login_validate")
                && !request.getServletPath().equals("/logout")){
            if(request.getSession().getAttribute("admin") == null){
                request.setAttribute("failMsg","管理员未登录，不可操作！！");
                request.getRequestDispatcher("/login").forward(request,servletResponse);
                return;
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("destroy");
    }
}
